package com.dayatang.product.webapp.action.trial;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.dayatang.excel.ExcelWriter;
import com.dayatang.product.domain.ProductTrial;
import com.dayatang.product.webapp.action.BaseAction;
import com.dayatang.product.webapp.annotation.PMLog;

public class TrialCodeExportExcelAction extends BaseAction {

	private static final long serialVersionUID = -432495709230652063L;
	
	private File outputFile;
	
	private long[] trialIds;
	
	@Action(results = {
			@Result(name = "success", type = "stream", params = {"inputName", "inputStream","contentDisposition","attachment;filename=${downloadFileName}"}),
			@Result(name = "input", type = "redirect",location="/mail/html-mail-manage.action") })
	@PMLog(moduleName = "试用号管理", option = "导出试用号")
	public String execute() throws Exception {
		outputFile = new File("试用号列表.xls");
		ExcelWriter instance = new ExcelWriter(outputFile);
		List<Object[]> data = createData();
		instance.write("试用号", 0, 0, data);
		return SUCCESS;
	}

	public long[] getTrialIds() {
		return trialIds;
	}

	public void setTrialIds(long[] trialIds) {
		this.trialIds = trialIds;
	}
	
	public InputStream getInputStream() throws FileNotFoundException {
		return new FileInputStream(outputFile);
	}

    public String getDownloadFileName() throws UnsupportedEncodingException{
        return new String("试用号列表.xls".getBytes(), "ISO8859-1");
    }
    
    private List<Object[]> createData() {
		List<Object[]> results = new ArrayList<Object[]>();
		if (trialIds != null) {
			for (long trialId : trialIds) {
				ProductTrial productTrial = ProductTrial.get(ProductTrial.class, trialId);
				if (productTrial != null) {
					results.add(new Object[] {"客户名称","产品名称","试用号","客户地址"});
					results.add(new Object[] {productTrial.getCustomerInfo().getCompanyName(), productTrial.getProduct().getName(), productTrial.getTrialCode().getTrialNum(), productTrial.getCustomerInfo().getAddress()});
				}
			}
		}
		return results;
	}

}
